package com.ruoyi.pack.controller;

import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.system.domain.ShipmentTrack;
import com.ruoyi.system.service.IShipmentTrackService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestParam;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.pack.domain.WayBill;
import com.ruoyi.pack.service.IWayBillService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 运单管理Controller
 *
 * @author ruoyi
 * @date 2025-08-07
 */
@RestController
@RequestMapping("/system/bill")
public class WayBillController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(WayBillController.class);
    
    private final IWayBillService wayBillService;
    private final IShipmentTrackService shipmentTrackService;

    public WayBillController(IWayBillService wayBillService, IShipmentTrackService shipmentTrackService) {
        this.wayBillService = wayBillService;
        this.shipmentTrackService = shipmentTrackService;
    }

    /**
     * 查询运单列表
     */
    @PreAuthorize("@ss.hasPermi('system:bill:list')")
    @GetMapping("/list")
    public TableDataInfo list(WayBill wayBill)
    {
        log.info("查询运单列表，参数：{}", wayBill);
        log.info("运单编号：{}，运单状态：{}，发货方：{}，收货方：{}，开始时间：{}，结束时间：{}", 
                wayBill.getBillNo(), wayBill.getBillStatus(), wayBill.getSenderName(), 
                wayBill.getReceiverName(), wayBill.getBeginTime(), wayBill.getEndTime());
        if (StringUtils.isNotEmpty(wayBill.getSortColumnsStr())) {
            log.info("排序条件：{}", wayBill.getSortColumnsStr());
        } else {
            log.info("排序条件：无，使用默认排序");
        }
        
        // 临时注释分页，测试查询是否正常
        // startPage();
        List<WayBill> list = wayBillService.selectWayBillList(wayBill);
        log.info("不使用分页时查询结果：{}", list.size());
        
        log.info("查询结果数量：{}", list.size());
        return getDataTable(list);
    }

    /**
     * 导出运单列表
     */
    @PreAuthorize("@ss.hasPermi('system:bill:export')")
    @Log(title = "运单管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, @RequestBody WayBill wayBill)
    {
        log.info("导出运单列表，参数：{}", wayBill);
        
        List<WayBill> list;
        
        // 如果指定了IDs，则按ID导出
        if (wayBill.getIds() != null && !wayBill.getIds().isEmpty()) {
            log.info("按指定ID导出，ID数量：{}", wayBill.getIds().size());
            list = wayBillService.listByIds(wayBill.getIds());
        } else {
            // 按查询条件导出
            log.info("按查询条件导出");
            list = wayBillService.selectWayBillList(wayBill);
        }
        
        log.info("导出数据数量：{}", list.size());
        
        ExcelUtil<WayBill> util = new ExcelUtil<WayBill>(WayBill.class);
        util.exportExcel(response, list, "运单数据");
    }

    /**
     * 获取运单详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:bill:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        log.info("查询运单详情，ID：{}", id);
        if (StringUtils.isEmpty(id)) {
            return error("运单ID不能为空");
        }
        
        WayBill wayBill = wayBillService.getById(id);
        if (wayBill == null) {
            return error("运单不存在");
        }
        
        return success(wayBill);
    }

    /**
     * 新增运单
     */
    @PreAuthorize("@ss.hasPermi('system:bill:add')")
    @Log(title = "运单管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody WayBill wayBill)
    {
        log.info("新增运单，数据：{}", wayBill);
        log.info("发货方省市区信息：province={}, city={}, district={}", 
            wayBill.getSenderProvince(), wayBill.getSenderCity(), wayBill.getSenderDistrict());
        log.info("收货方省市区信息：province={}, city={}, district={}", 
            wayBill.getReceiverProvince(), wayBill.getReceiverCity(), wayBill.getReceiverDistrict());
        log.info("收货方坐标信息：longitude={}, latitude={}", 
            wayBill.getReceiverLongitude(), wayBill.getReceiverLatitude());
        
        try {
            // 基本参数校验
            if (StringUtils.isEmpty(wayBill.getBillNo())) {
                return error("运单编号不能为空");
            }
            
            // 设置创建信息
            wayBill.setCreateBy(getUsername());
            wayBill.setCreateTime(new java.util.Date());
            
            boolean result = wayBillService.save(wayBill);
            
            if (result) {
                log.info("新增运单成功，运单号：{}", wayBill.getBillNo());
                return success("新增成功");
            } else {
                log.error("新增运单失败，运单号：{}", wayBill.getBillNo());
                return error("新增失败");
            }
            
        } catch (Exception e) {
            log.error("新增运单异常，运单号：{}，错误信息：{}", wayBill.getBillNo(), e.getMessage(), e);
            return error("新增失败：" + e.getMessage());
        }
    }

    /**
     * 修改运单
     */
    @PreAuthorize("@ss.hasPermi('system:bill:edit')")
    @Log(title = "运单管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WayBill wayBill)
    {
        log.info("修改运单，数据：{}", wayBill);
        log.info("发货方省市区信息：province={}, city={}, district={}", 
            wayBill.getSenderProvince(), wayBill.getSenderCity(), wayBill.getSenderDistrict());
        log.info("收货方省市区信息：province={}, city={}, district={}", 
            wayBill.getReceiverProvince(), wayBill.getReceiverCity(), wayBill.getReceiverDistrict());
        log.info("收货方坐标信息：longitude={}, latitude={}", 
            wayBill.getReceiverLongitude(), wayBill.getReceiverLatitude());
        
        try {
            // 基本参数校验
            if (StringUtils.isEmpty(wayBill.getId())) {
                return error("运单ID不能为空");
            }
            
            // 检查运单是否存在
            WayBill existWayBill = wayBillService.getById(wayBill.getId());
            if (existWayBill == null) {
                return error("运单不存在");
            }
            
            // 设置更新信息
            wayBill.setUpdateBy(getUsername());
            wayBill.setUpdateTime(new java.util.Date());
            
            boolean result = wayBillService.updateById(wayBill);
            
            if (result) {
                log.info("修改运单成功，运单ID：{}", wayBill.getId());
                return success("修改成功");
            } else {
                log.error("修改运单失败，运单ID：{}", wayBill.getId());
                return error("修改失败");
            }
            
        } catch (Exception e) {
            log.error("修改运单异常，运单ID：{}，错误信息：{}", wayBill.getId(), e.getMessage(), e);
            return error("修改失败：" + e.getMessage());
        }
    }

    /**
     * 删除运单
     */
    @PreAuthorize("@ss.hasPermi('system:bill:remove')")
    @Log(title = "运单管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        log.info("删除运单，IDs：{}", Arrays.toString(ids));
        
        try {
            if (ids == null || ids.length == 0) {
                return error("请选择要删除的运单");
            }
            
            boolean result = wayBillService.removeByIds(Arrays.asList(ids));
            
            if (result) {
                log.info("删除运单成功，IDs：{}", Arrays.toString(ids));
                return success("删除成功");
            } else {
                log.error("删除运单失败，IDs：{}", Arrays.toString(ids));
                return error("删除失败");
            }
            
        } catch (Exception e) {
            log.error("删除运单异常，IDs：{}，错误信息：{}", Arrays.toString(ids), e.getMessage(), e);
            return error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 查询运单轨迹列表
     */
    @PreAuthorize("@ss.hasPermi('logistics:shipment:query')")
    @GetMapping("/track")
    @Log(title = "运单轨迹", businessType = BusinessType.OTHER)
    public AjaxResult getShipmentTrack(@RequestParam String shipmentId, @RequestParam(required = false) String viewMode)
    {
        try {
            log.info("查询运单轨迹，运单ID：{}，查看模式：{}", shipmentId, viewMode);
            
            if (StringUtils.isEmpty(shipmentId)) {
                return error("运单ID不能为空");
            }
            
            // 查询运单信息
            WayBill wayBill = wayBillService.getById(shipmentId);
            if (wayBill == null) {
                return error("运单不存在");
            }
            
            // 查询轨迹列表
            List<ShipmentTrack> trackingList = shipmentTrackService.selectTrackByShipmentId(shipmentId);
            
            // 构建返回数据
            AjaxResult result = AjaxResult.success();
            result.put("shipmentInfo", wayBill);
            result.put("trackingList", trackingList);
            
            // 如果是按天查看模式，则按天分组
            if ("daily".equals(viewMode)) {
                // 这里可以根据需要实现按天分组的逻辑
                // 暂时返回原始数据
                result.put("dailyTracking", trackingList);
            }
            
            log.info("查询运单轨迹成功，运单ID：{}，轨迹数量：{}", shipmentId, trackingList.size());
            return result;
            
        } catch (Exception e) {
            log.error("查询运单轨迹异常，运单ID：{}，错误信息：{}", shipmentId, e.getMessage(), e);
            return error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 查询运单轨迹列表（通用接口）
     */
    @PreAuthorize("@ss.hasPermi('logistics:shipment:query')")
    @GetMapping("/tracks")
    @Log(title = "运单轨迹列表", businessType = BusinessType.OTHER)
    public TableDataInfo getShipmentTracks(ShipmentTrack shipmentTrack)
    {
        try {
            log.info("查询运单轨迹列表，查询条件：{}", shipmentTrack.toString());
            
            startPage();
            List<ShipmentTrack> list = shipmentTrackService.selectShipmentTrackList(shipmentTrack);
            
            log.info("查询运单轨迹列表成功，数量：{}", list.size());
            return getDataTable(list);
            
        } catch (Exception e) {
            log.error("查询运单轨迹列表异常，查询条件：{}，错误信息：{}", shipmentTrack.toString(), e.getMessage(), e);
            return getDataTable(Arrays.asList());
        }
    }

    // ==================== 位置跟踪相关接口 ====================
    
    /**
     * 绑定运单与定位器
     */
    @PreAuthorize("@ss.hasPermi('system:bill:edit')")
    @Log(title = "绑定运单定位器", businessType = BusinessType.UPDATE)
    @PutMapping("/{id}/bind-locator")
    public AjaxResult bindLocator(@PathVariable String id, @RequestParam Long locatorId, @RequestParam String locatorCode) {
        try {
            int result = wayBillService.bindLocator(id, locatorId, locatorCode);
            if (result > 0) {
                return success("绑定定位器成功");
            } else {
                return error("绑定定位器失败");
            }
        } catch (Exception e) {
            log.error("绑定运单定位器异常", e);
            return error("绑定定位器异常: " + e.getMessage());
        }
    }
    
    /**
     * 解绑运单与定位器
     */
    @PreAuthorize("@ss.hasPermi('system:bill:edit')")
    @Log(title = "解绑运单定位器", businessType = BusinessType.UPDATE)
    @PutMapping("/{id}/unbind-locator")
    public AjaxResult unbindLocator(@PathVariable String id) {
        try {
            int result = wayBillService.unbindLocator(id);
            if (result > 0) {
                return success("解绑定位器成功");
            } else {
                return error("解绑定位器失败");
            }
        } catch (Exception e) {
            log.error("解绑运单定位器异常", e);
            return error("解绑定位器异常: " + e.getMessage());
        }
    }
    

    
    /**
     * 查询延迟运单列表
     */
    @PreAuthorize("@ss.hasPermi('system:bill:list')")
    @GetMapping("/delayed")
    public TableDataInfo getDelayedWayBills() {
        try {
            List<WayBill> list = wayBillService.selectDelayedWayBills();
            return getDataTable(list);
        } catch (Exception e) {
            log.error("查询延迟运单列表异常", e);
            return getDataTable(Arrays.asList());
        }
    }
    
    /**
     * 查询待交接运单列表
     */
    @PreAuthorize("@ss.hasPermi('system:bill:list')")
    @GetMapping("/pending-handover")
    public TableDataInfo getPendingHandoverWayBills() {
        try {
            List<WayBill> list = wayBillService.selectPendingHandoverWayBills();
            return getDataTable(list);
        } catch (Exception e) {
            log.error("查询待交接运单列表异常", e);
            return getDataTable(Arrays.asList());
        }
    }
}
